package com.tianqi.autoSendTianqi.util;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class MailUtils
{
    private static final Logger log = LoggerFactory.getLogger(MailUtils.class);
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;

    public void sendSimpleMail(String to, String subject, String content)
    {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setFrom(this.from);
        message.setSubject(subject);
        message.setText(content);

        this.mailSender.send(message);
    }

    public void sendHtmlMail(String to, String subjecr, String content)
    {
        MimeMessage message = this.mailSender.createMimeMessage();
        try
        {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setFrom(this.from);
            helper.setSubject(subjecr);
            helper.setText(content, true);
            this.mailSender.send(message);
            log.info("发送静态邮件成功");
        }
        catch (MessagingException e)
        {
            log.error("发送静态邮件失败：", e);
        }
    }
}
